package cn.catsdad.service.impl;

import cn.catsdad.base.service.impl.BaseServiceImpl;
import cn.catsdad.dto.RoleUserDTO;
import cn.catsdad.repository.RoleUserRepository;
import cn.catsdad.service.api.RoleUserService;
import cn.catsdad.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 角色与用户关联service实现
 *
 * @author xuyonglong
 * @version V1.0 2023/4/13
 */
@Service
public class RoleUserServiceImpl extends BaseServiceImpl<RoleUserDTO, Long, RoleUserRepository>
        implements RoleUserService {

    @Override
    public List<Long> queryRoleIdByUserIdIn(Collection<Long> userIds) {
        List<Long> result = new ArrayList<>();
        if (StringUtil.isNotEmpty(userIds)) {
            List<RoleUserDTO> roleUsers = repository.findByUserIdIn(userIds);
            result = roleUsers.stream().map(RoleUserDTO::getRoleId).distinct().collect(Collectors.toList());
        }
        return result;
    }

    @Override
    public Map<Long, List<Long>> queryRolesByUserIds(Collection<Long> userIds) {
        Map<Long, List<Long>> result = new HashMap<>(userIds.size());
        if (StringUtil.isNotEmpty(userIds)) {
            result = repository.findByUserIdIn(userIds).stream()
                    .collect(Collectors.groupingBy(RoleUserDTO::getUserId,
                            Collectors.mapping(RoleUserDTO::getRoleId, Collectors.toList())));
        }
        return result;
    }

    @Override
    @Transactional
    public void deleteByUserIds(Collection<Long> userIds) {
        if (StringUtil.isNotEmpty(userIds)) {
            repository.deleteByUserIdIn(userIds);
        }
    }

    @Override
    @Transactional
    public void deleteByRoleIds(Collection<Long> roleIds) {
        if (StringUtil.isNotEmpty(roleIds)) {
            repository.deleteByRoleIdIn(roleIds);
        }
    }

}
